package node.exp;

import grammar.Lexer;
import grammar.MyError;
import lexical.Key;
import node.Node;
import symbol.SymbolTable;

import java.util.ArrayList;

public class PrimaryExp implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private Node primaryExp;
    public ArrayList<Node> nodes = new ArrayList<>();

    public PrimaryExp(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parsePrimaryExp();
    }

    private void parsePrimaryExp() {
        if (lexer.isWordType(0, Key.LPARENT)) {
            nodes.add(lexer.getCurWord()); // (
            primaryExp = new Exp(lexer, table, this);
            nodes.add(primaryExp);
            if (lexer.isWordType(0, Key.RPARENT)) {
                nodes.add(lexer.getCurWord()); // )
            } else {
                lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
            }
        } else if (lexer.isWordType(0, Key.IDENFR)) {
            primaryExp = new LVal(lexer, table, this);
            nodes.add(primaryExp);
        } else {
            primaryExp = new Number(lexer, table, this);
            nodes.add(primaryExp);
        }
    }

    public int getValue() {
        if (primaryExp instanceof Exp) {
            return ((Exp) primaryExp).getValue();
        } else if (primaryExp instanceof LVal) {
            return ((LVal) primaryExp).getValue();
        } else if (primaryExp instanceof Number) {
            return ((Number) primaryExp).getValue();
        }
        return 0;
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<PrimaryExp>\n").toString();
    }

    @Override
    public String genMidCode() {
        return primaryExp.genMidCode();
    }
}

